from glob import glob
import os
from tqdm import tqdm


def get_sign(dat_r):
    signatures = [(0x89, 0x50, 0x4e), (0x47, 0x49, 0x46), (0xff, 0xd8, 0xff)]
    mats = [".png", ".gif", ".jpg"]
    for now in dat_r:
        for j, xor in enumerate(signatures):
            res = [nowByte ^ xor_byte for nowByte,
            xor_byte in zip(now[:3], xor)]
            if res[0] == res[1] == res[2]:
                return res[0], mats[j]
    else:
        raise Exception("no valid signature is found")


def imageDecode(file, root_path, dest_path=None):
    dat_r = open(file, "rb")
    try:
        sign, mat = get_sign(dat_r)
        dat_r.seek(0)
        data = bytes(byte ^ sign for byte in dat_r.read())
        relative_path = os.path.relpath(file, root_path)
        if dest_path is None:
            dest_path = os.path.join(root_path, "CovertImage")
        dest = os.path.join(dest_path,
                            relative_path.replace(".dat", mat))
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        with open(dest, "wb") as write:
            write.write(data)
    finally:
        dat_r.close()


def main(into_path, out_path=None):
    for file in tqdm(glob(os.path.join(into_path, "**", "*.dat"), recursive=True)):
        imageDecode(file, into_path, out_path)


if __name__ == '__main__':
    # 6f13e582b1ea7edb3ce9dac0a4e2f58b  张宛腾班级群
    into_path = r"D:\Mail&IM\WeChat\WeChat Files\wxid_4s2g2inx5cc221\FileStorage\MsgAttach\6f13e582b1ea7edb3ce9dac0a4e2f58b\Image"
    # out_path = r"D:\Mail&IM\WeChat\WeChat Files\wxid_4s2g2inx5cc221\FileStorage\MsgAttach\0c27fdff80c031baa2bce5a08336ecaa\Thumb\2024-07"
    # 输入输出在一个目录
    main(into_path, into_path)